/*
 * Copyright (C) 2011 Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * pn_Targets.java
 *
 * Created on 11/07/2011, 15:22:02
 */
package kuasar.plugin.deployer.gui;

import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import kuasar.plugin.Intercom.GUI;
import kuasar.plugin.deployer.Config;
import kuasar.plugin.deployer.gui.classmod.pn_TableCellRenderer;
import kuasar.plugin.deployer.gui.classmod.I_Panels;
import kuasar.plugin.utils.XML;
import org.jdom.Element;

/**
 *
 * @author Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 */
public class pn_Targets extends kuasar.plugin.classMod.AbstractPanel implements I_Panels{
    private DefaultTreeModel tm_Projects = new DefaultTreeModel(new DefaultMutableTreeNode(null));
    private DefaultTreeModel tm_Servers = new DefaultTreeModel(new DefaultMutableTreeNode(null));
    
    /** Creates new form pn_Targets */
    public pn_Targets() {
        initComponents();
        loadProjects();
        loadTargets();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbl_Projects = new javax.swing.JLabel();
        lbl_Targets = new javax.swing.JLabel();
        spn_Projects = new javax.swing.JScrollPane();
        tre_Projects = new javax.swing.JTree();
        spn_Targets = new javax.swing.JScrollPane();
        tre_Targets = new javax.swing.JTree();
        Title = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        btn_Next = new javax.swing.JButton();

        setOpaque(false);

        lbl_Projects.setFont(new java.awt.Font("Dialog", 1, 18));
        lbl_Projects.setForeground(new java.awt.Color(204, 204, 204));
        lbl_Projects.setText("Projects:");

        lbl_Targets.setFont(new java.awt.Font("Dialog", 1, 18));
        lbl_Targets.setForeground(new java.awt.Color(204, 204, 204));
        lbl_Targets.setText("Targets:");

        spn_Projects.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_Projects.setViewportBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_Projects.setOpaque(false);

        tre_Projects.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        tre_Projects.setModel(tm_Projects);
        tre_Projects.setCellRenderer(new pn_TableCellRenderer());
        tre_Projects.setOpaque(false);
        tre_Projects.setRootVisible(false);
        spn_Projects.setViewportView(tre_Projects);
        tre_Projects.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

        spn_Targets.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_Targets.setViewportBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_Targets.setOpaque(false);

        tre_Targets.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        tre_Targets.setModel(tm_Servers);
        tre_Targets.setCellRenderer(new pn_TableCellRenderer());
        tre_Targets.setOpaque(false);
        tre_Targets.setRootVisible(false);
        spn_Targets.setViewportView(tre_Targets);
        tre_Targets.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

        Title.setFont(new java.awt.Font("Dialog", 1, 28));
        Title.setForeground(new java.awt.Color(204, 204, 204));
        Title.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/deployer/icons/selection48.png"))); // NOI18N
        Title.setText("Select");

        jPanel1.setOpaque(false);

        btn_Next.setBackground(new java.awt.Color(0, 0, 0));
        btn_Next.setForeground(new java.awt.Color(204, 204, 204));
        btn_Next.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/deployer/icons/next22.png"))); // NOI18N
        btn_Next.setText("Next");
        btn_Next.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_Next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_NextActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(442, Short.MAX_VALUE)
                .addComponent(btn_Next)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btn_Next)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(Title, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(spn_Projects, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spn_Targets, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lbl_Projects, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbl_Targets, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Title, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_Targets)
                    .addComponent(lbl_Projects))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(spn_Targets, 0, 0, Short.MAX_VALUE)
                    .addComponent(spn_Projects, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        spn_Projects.getViewport().setOpaque(false);
        spn_Targets.getViewport().setOpaque(false);
    }// </editor-fold>//GEN-END:initComponents

    private void btn_NextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_NextActionPerformed
        goNext();
    }//GEN-LAST:event_btn_NextActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Title;
    private javax.swing.JButton btn_Next;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbl_Projects;
    private javax.swing.JLabel lbl_Targets;
    private javax.swing.JScrollPane spn_Projects;
    private javax.swing.JScrollPane spn_Targets;
    private javax.swing.JTree tre_Projects;
    private javax.swing.JTree tre_Targets;
    // End of variables declaration//GEN-END:variables

    private void loadProjects() {
        Element root = XML.getRoot(Config.VMdir, Config.VMdata);
        tm_Projects.setRoot(addRecursiveElements(root, new DefaultMutableTreeNode(null)));
    }
    
    private void loadTargets() {
        Element root = XML.getRoot(Config.SMdir,Config.SMdata);
        DefaultMutableTreeNode node=addRecursiveElements(root, new DefaultMutableTreeNode(null));
        tm_Servers.setRoot(node);
    }

    private DefaultMutableTreeNode addRecursiveElements(Element root, DefaultMutableTreeNode rootnode) {
        TreeMap<String,DefaultMutableTreeNode> tm= new TreeMap<String,DefaultMutableTreeNode>();
        List children = root.getChildren();
        for(int i=0; i<children.size();i++){
            Element child = (Element) children.get(i);
            if(child.getAttributeValue("type").isEmpty()){
                String data[] = {child.getName(),child.getAttributeValue("name"),"",null};
                DefaultMutableTreeNode node = addRecursiveElements(child,new DefaultMutableTreeNode(data));
                tm.put(child.getAttributeValue("name"), node);
            }
        }
        Iterator it=tm.keySet().iterator();
        while(it.hasNext()){
            rootnode.add(tm.get((String)it.next()));
        }
        tm.clear();
        for(int i=0; i<children.size();i++){
            Element child = (Element) children.get(i);
            if(!child.getAttributeValue("type").isEmpty()){
                String data[] = {child.getName(),child.getAttributeValue("name"),child.getAttributeValue("type"),child.getAttributeValue("icon")};
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(data);
                tm.put(child.getAttributeValue("name"), node);
            }
        }
        it=tm.keySet().iterator();
        while(it.hasNext()){
            rootnode.add(tm.get((String)it.next()));
        }
        return rootnode;
    }
    
    private Element getTreeElement(Element root, JTree tree){
        if(tree.getSelectionCount()==0) return root;
        Object[] nodes = tree.getSelectionPath().getPath();
        String path = "";
        DefaultMutableTreeNode node;
        for(int i = 0; i<nodes.length; i++){
            node = (DefaultMutableTreeNode) nodes[i];
            path+=getXMLName(node);
        }
        if(path.isEmpty())path="/";
        return XML.getElementOnPath(path, root);
    }
    private String getXMLName(DefaultMutableTreeNode node){
        if(node.getUserObject() == null) return "";
        String[] data = (String[]) node.getUserObject();
        return "/" + data[0];
    }

    @Override
    public void goNext() {
        Element projectNode =getTreeElement(XML.getRoot(Config.VMdir, Config.VMdata), tre_Projects);
        Element targetNode = getTreeElement(XML.getRoot(Config.SMdir, Config.SMdata),tre_Targets);
        pn_Checker checker = new pn_Checker(projectNode,targetNode,this);
        GUI.loadPlugin(checker);
        checker.start();
    }

    @Override
    public void goPrevious() {
        throw new UnsupportedOperationException("Not supported.");
    }

}
